package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired CheckInMapper checkInMapper;
    @Autowired ElderMapper elderMapper;
    @Autowired BedMapper bedMapper;
    @Autowired CheckInConfigMapper checkInConfigMapper;
    @Autowired ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否入住，通过身份证号查询老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        queryWrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elder)){
            throw new RuntimeException("该老人已入住");
        }
        //更新床位状态
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //保存或更新老人数据
        elder = insertOrUpdateElder(bed,dto.getCheckInElderDto());
        //生成合同编号
        String contractNo = "HT"+ CodeGenerator.generateContractNumber();
        // 新增合同
        insertContract(contractNo, elder, dto);
        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);
        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);
    }
    /**
     * 新增或更新老人
     * @param bed
     * @param dto
     * @return
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto dto) {
        //设定一个老人对象，接收数据
        Elder elder = new Elder();
        //拷贝老人属性
        BeanUtils.copyProperties(dto, elder);
        //补齐老人的剩余属性
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //查询老人信息，判断该老人是否存在，如果存在则更新，不存在则新增
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, dto.getIdCardNo()).ne(Elder::getStatus,1);
        Elder elder1 = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elder1)){
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;
    }
    /**
     * 新增合同
     * @param contractNo
     * @param elder
     * @param dto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        //拷贝并补全合同属性
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        LocalDateTime checkInStartTime  = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }
    /**
     * 新增入住信息
     * @param elder
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }
    /**
     * 新增入住配置
     * @param dto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }
}
